/*
 * @lc app=leetcode.cn id=150 lang=javascript
 *
 * [150] 逆波兰表达式求值
 */

// @lc code=start
/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function (tokens) {
  if (tokens.length === 1) return Number(tokens[0]);
  const stack = [];
  const calList = ["+", "-", "*", "/"];
  function calculator(x, y, cal) {
    x = Number(x);
    y = Number(y);
    if (cal === "+") return x + y;
    if (cal === "-") return x - y;
    if (cal === "*") return x * y;
    if (cal === "/" && x / y < 0) return Math.ceil(x / y);
    if (cal === "/" && x / y >= 0) return Math.floor(x / y);
  }
  for (const ch of tokens) {
    if (calList.includes(ch)) {
      const x = stack.pop();
      const y = stack.pop();
      stack.push(calculator(y, x, ch));
    } else {
      stack.push(ch);
    }
  }
  return stack[0];
};
// @lc code=end
